<?php
if (!defined('IN_PLUGIN')) exit();

// the @ symbol is Error Control Operators, 如果出错, 则压制错误显示
@header('Content-Type: text/html; charset=UTF-8');

require_once(PAY_ROOT . "inc/AlipayTradeService.php");

$logfile_name = date('Ymd') . '-return' . '.log';
// mylog($logfile_name, json_encode($_GET));

/**
 * http://epay.mandong8.com/plugins/alipay/return.php/?
 * 
 * charset=UTF-8
 * &out_trade_no=2023112914534282925
 * &method=alipay.trade.page.pay.return
 * &total_amount=1.00
 * &sign=P2x9J%2FOOFDD4MGRlerxL18LQUM6SkONpl74jDS%2FXmNzwhYdrJtNwkVE21VYdqmbgRL7tawSvSdHI9i2gVAU82LzHWNVxJFmliVNMcR3oCjaRRzNqLbR479meqKyWjrR12SW9d1rfetnkytggQKPARwhFecDJUBTL1POlmUabY7qFtsD9OGZ0rFswwMjP5GumtEzb5kExWISurpgphvNmOcvxWbHcXZjDjQHwLgyPds8y9ISBigCU3ZRN69gFWlZWi%2FhVmhvZSo0BmiqvuHHUGxsdTh4GkvxqgfPJ21Uk6rEoBlnTxE2fesURlLFG2PnL7n%2FHr5cdEmbdwVK1PtcxaA%3D%3D
 * &trade_no=2023112922001480880501460289
 * &auth_app_id=9021000132627757
 * &version=1.0
 * &app_id=9021000132627757
 * &sign_type=RSA2
 * &seller_id=2088721022863072
 * &timestamp=2023-11-29+14%3A54%3A11
 */

//计算得出通知验证结果
$alipaySevice = new AlipayTradeService($config);
//$alipaySevice->writeLog(var_export($_POST,true));
$verify_result = $alipaySevice->check($_GET);

if ($verify_result) { //验证成功
	//商户订单号
	$out_trade_no = daddslashes($_GET['out_trade_no']);

	//支付宝交易号
	$trade_no = daddslashes($_GET['trade_no']);

	//交易金额
	$total_amount = $_GET['total_amount'];

	// 订单
	$order = $DB->getRow("SELECT * FROM pre_order WHERE `trade_no` = '{$_GET['out_trade_no']}' ");
	if (!$order) {
		// 没有这个订单...
		mylog($logfile_name, 'fail-noorder');
		sysmsg('没有该订单' . $_GET['out_trade_no']);
	}

	if ($out_trade_no == TRADE_NO && round($total_amount, 2) == round($order['realmoney'], 2)) {
		$url = creat_callback($order);

		if ($order['status'] == 0) {
			if ($DB->exec("update `pre_order` set `status` ='1' where `trade_no`='" . TRADE_NO . "'")) {
				$DB->exec("update `pre_order` set `api_trade_no` ='$trade_no',`endtime` ='$date',`date` =NOW() where `trade_no`='" . TRADE_NO . "'");
				processOrder($order, false);
			}
		}
		returnTemplate($url['return']);
	} else {
		sysmsg('订单信息校验失败');
	}
} else {
	//验证失败
	sysmsg('支付宝返回验证失败！');
}
?>